package com.sls.nzdapplication.db.utils;

//import static com.sls.nzdapplication.util.UuidUtils.id;

import android.content.Context;


import com.alibaba.fastjson.JSONArray;
import com.sls.nzdapplication.db.DaoManager;
import com.sls.nzdapplication.db.DaoSession;
import com.sls.nzdapplication.db.EquipmentDao;
import com.sls.nzdapplication.model.Equipment;
import com.sls.nzdapplication.app.MySharedPreferences;

import org.greenrobot.greendao.query.QueryBuilder;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;

public class EquipmentUtil {
    private static final boolean DUBUG = true;
    private DaoManager manager;
    private com.sls.nzdapplication.model.Equipment Equipment;
    private DaoSession daoSession;
    private MySharedPreferences mySharedPreferences;
    private String username = "";

    public EquipmentUtil(Context context) {
        manager = DaoManager.getInstance();
        manager.init(context);
        daoSession = manager.getDaoSession();
        manager.setDebug(DUBUG);
        mySharedPreferences = new MySharedPreferences(context);
        username = mySharedPreferences.getUserValue("username");
    }

    /**
     * 添加数据，如果有重复则覆盖
     */
    public void insertEquipment(Equipment equipment) {
        equipment.setCreateBy(username);
        equipment.setCreateTime(new Date());
        manager.getDaoSession().insertOrReplace(equipment);
    }


    /**
     * 添加多条数据，需要开辟新的线程
     */
    public void insertMultEquipment(final List<Equipment> equipments) {
        manager.getDaoSession().runInTx(new Runnable() {
            @Override
            public void run() {
                for (Equipment equipment : equipments) {
                    equipment.setCreateBy(username);
                    equipment.setCreateTime(new Date());
                    manager.getDaoSession().insertOrReplace(equipment);
                }
            }
        });
    }

    /**
     * 添加多条数据，需要开辟新的线程
     */
    public void insertMultEquipment2(final List<Equipment> equipments) {
        manager.getDaoSession().runInTx(new Runnable() {
            @Override
            public void run() {
                for (Equipment equipment : equipments) {
                    manager.getDaoSession().insertOrReplace(equipment);
                }
            }
        });
    }

    /**
     * 删除数据
     */
    public void deleteEquipment(Equipment equipment) {
        manager.getDaoSession().delete(equipment);
    }

    /**
     * 删除全部数据
     */
    public void deleteAll(Class cls) {
        manager.getDaoSession().deleteAll(cls);
    }

    /**
     * 更新数据
     */
    public void updateEquipment(Equipment equipment) {
        equipment.setModifyBy(username);
        equipment.setModifyTime(new Date());
        manager.getDaoSession().update(equipment);
    }

    /**
     * 按照主键返回单条数据
     */
    public Equipment listOneEquipment(String key) {
        return manager.getDaoSession().load(Equipment.class, key);
    }

    public List<Equipment> queryEquipmentByLineId(String id) {
        QueryBuilder<Equipment> builder = manager.getDaoSession().queryBuilder(Equipment.class);
        List<Equipment> equipmentList = builder.where(EquipmentDao.Properties.WorkLineId.eq(id)).orderAsc(EquipmentDao.Properties.CreateTime).list();
        return equipmentList;
    }

    public List<Equipment> queryEquipmentByAreaIdAndexqIdAndType(String id, String exqId, String type) {
        QueryBuilder<Equipment> builder = manager.getDaoSession().queryBuilder(Equipment.class);
        List<Equipment> equipmentList;
        if (type.equals("电站")) {
            equipmentList = builder.where(builder.and(EquipmentDao.Properties.WorkLineId.eq(id), EquipmentDao.Properties.PreviousEquipmentId.eq(exqId), builder.or(EquipmentDao.Properties.Type.eq("环网柜"),
                    EquipmentDao.Properties.Type.eq("分支箱"),
                    EquipmentDao.Properties.Type.eq("开关站"),
                    EquipmentDao.Properties.Type.eq("开闭所"),
                    EquipmentDao.Properties.Type.eq("配电室"),
                    EquipmentDao.Properties.Type.eq("箱变")
            ))).list();
        } else if (type.equals("开关")) {
            equipmentList = builder.where(builder.and(EquipmentDao.Properties.WorkLineId.eq(id), EquipmentDao.Properties.PreviousEquipmentId.eq(exqId), builder.or(EquipmentDao.Properties.Type.eq("柱上负荷开关"),
                    EquipmentDao.Properties.Type.eq("断路器"),
                    EquipmentDao.Properties.Type.eq("隔离开关")))).list();
        } else if (type.equals("公用变")) {
            equipmentList = builder.where(builder.and(EquipmentDao.Properties.WorkLineId.eq(id), EquipmentDao.Properties.PreviousEquipmentId.eq(exqId), builder.or(EquipmentDao.Properties.Type.eq("公用配电变压器"),
                    EquipmentDao.Properties.Type.eq("公用柱上变压器"),
                    EquipmentDao.Properties.Type.eq("用户专变")))).list();
        } else {
            equipmentList = builder.where(builder.and(EquipmentDao.Properties.WorkLineId.eq(id), EquipmentDao.Properties.PreviousEquipmentId.eq(exqId), EquipmentDao.Properties.Type.eq(type))).orderDesc(EquipmentDao.Properties.CreateTime).list();

        }
        return equipmentList;
    }


    public List<Equipment> queryEquipmentByLineIdAndNoSelf(String id, String eid, String query) {
        QueryBuilder<Equipment> builder = manager.getDaoSession().queryBuilder(Equipment.class);
        List<Equipment> equipmentList = builder.where(builder.and(EquipmentDao.Properties.WorkLineId.eq(id), EquipmentDao.Properties.Name.like("%" + query + "%"), EquipmentDao.Properties.Id.notEq(eid))).orderAsc(EquipmentDao.Properties.CreateTime).list();
        return equipmentList;
    }

    /**
     * 根据生产线ID和排除自身ID，查询设备信息。
     *
     * @param id    生产线的ID
     * @param eid   排除查询的设备ID（不查询此ID的设备）
     * @param query 查询文本，用于设备名称的模糊匹配
     * @return 返回匹配条件的设备数组
     */
    public Equipment[] queryEquipmentByLineIdAndNoSelfByte(String id, String eid, String query) {

        // 将查询文本处理成带有通配符的格式
        String likeQuery = "%" + query.replaceAll("(.)(?=.*)", "$1%") + "%";
        QueryBuilder<Equipment> builder = manager.getDaoSession().queryBuilder(Equipment.class);
        Equipment[] equipmentArray = builder
                .where(builder.and(EquipmentDao.Properties.WorkLineId.eq(id),
                        // 排除特定ID的设备，同时进行名称的模糊匹配
                        EquipmentDao.Properties.Id.notEq(eid),
                        EquipmentDao.Properties.Name.like(likeQuery)
                ))
                .orderAsc(EquipmentDao.Properties.CreateTime) // 按创建时间升序排序
                .list() // 执行查询并获得结果列表
                .toArray(new Equipment[0]); // 将查询结果列表转换为数组
        return equipmentArray;
    }

    //    根据输入内容查询
    public List<Equipment> queryEquipmentCustom(String query) {
        QueryBuilder<Equipment> builder = manager.getDaoSession().queryBuilder(Equipment.class);
        return builder.where(builder.or(EquipmentDao.Properties.Name.like("%" + query + "%"), EquipmentDao.Properties.Id.like("%" + query + "%"))).orderAsc(EquipmentDao.Properties.CreateTime).list();
    }


    public List<Equipment> queryEquipmentByLineId3(String id) {
        QueryBuilder<Equipment> builder = manager.getDaoSession().queryBuilder(Equipment.class);
        List<Equipment> equipmentList = builder.where(builder.and(EquipmentDao.Properties.WorkLineId.eq(id), EquipmentDao.Properties.PdxId.isNull())).orderAsc(EquipmentDao.Properties.CreateTime).list();
        return equipmentList;
    }

    public List<Equipment> queryEquipmentByLineId2(String id) {
        QueryBuilder<Equipment> builder = manager.getDaoSession().queryBuilder(Equipment.class);
        List<Equipment> equipmentList = builder.where(builder.and(EquipmentDao.Properties.WorkLineId.eq(id), EquipmentDao.Properties.PdxId.isNull())).orderDesc(EquipmentDao.Properties.CreateTime).list();
        return equipmentList;
    }

    /**
     * 根据生产线ID和设备名称查询设备信息。
     *
     * @param id 生产线的ID，用于查询特定生产线的设备。
     * @param name 设备的名称，用于查询具有特定名称的设备。
     * @return 返回一个设备列表，这些设备属于指定的生产线并且具有指定的名称。
     */
    public List<Equipment> queryEquipmentByLineIdAndName(String id, String name) {
        // 创建查询构建器，用于构建针对Equipment表的查询语句
        QueryBuilder<Equipment> builder = manager.getDaoSession().queryBuilder(Equipment.class);

        // 根据提供的生产线ID和设备名称进行查询，并执行查询操作，返回查询结果
        List<Equipment> equipmentList = builder.where(builder.and(EquipmentDao.Properties.WorkLineId.eq(id), EquipmentDao.Properties.Name.eq(name))).list();

        return equipmentList;
    }


    public boolean queryEquipmentByLineIdAndLxfs(String id, String name) {
        // 创建查询构建器，用于构建针对Equipment表的查询语句
        QueryBuilder<Equipment> builder = manager.getDaoSession().queryBuilder(Equipment.class);

        // 根据提供的生产线ID和设备名称进行查询，并执行查询操作，返回查询结果
        List<Equipment> equipmentList = builder.where(builder.and(EquipmentDao.Properties.WorkLineId.eq(id), EquipmentDao.Properties.Lxfs.eq(name))).list();
        // 检查查询结果是否为空
        return !equipmentList.isEmpty();
    }


    public List<Equipment> queryEquipmentByLineIdAndBdz(String id) {
        QueryBuilder<Equipment> builder = manager.getDaoSession().queryBuilder(Equipment.class);
        List<Equipment> equipmentList = builder.where(builder.and(EquipmentDao.Properties.WorkLineId.eq(id), EquipmentDao.Properties.Type.eq("变电站"))).list();
        return equipmentList;
    }

    public List<Equipment> queryEquipmentByLineIdAndDz(String id) {
        QueryBuilder<Equipment> builder = manager.getDaoSession().queryBuilder(Equipment.class);
        List<Equipment> equipmentList = builder.where(builder.and(EquipmentDao.Properties.WorkLineId.eq(id), builder.or(EquipmentDao.Properties.Type.eq("环网柜"),
                EquipmentDao.Properties.Type.eq("分支箱"),
                EquipmentDao.Properties.Type.eq("开关站"),
                EquipmentDao.Properties.Type.eq("开闭所"),
                EquipmentDao.Properties.Type.eq("配电室"),
                EquipmentDao.Properties.Type.eq("箱变")
        ))).list();
        return equipmentList;
    }

    public List<Equipment> queryEquipmentByLineIdAndKg(String id) {
        QueryBuilder<Equipment> builder = manager.getDaoSession().queryBuilder(Equipment.class);
        List<Equipment> equipmentList = builder.where(builder.and(EquipmentDao.Properties.WorkLineId.eq(id), builder.or(EquipmentDao.Properties.Type.eq("柱上负荷开关"),
                EquipmentDao.Properties.Type.eq("跌落式熔断器"),
                EquipmentDao.Properties.Type.eq("断路器"),
                EquipmentDao.Properties.Type.eq("隔离开关")
        ))).list();
        return equipmentList;
    }

    public List<Equipment> queryEquipmentByLineIdAndGyb(String id) {
        QueryBuilder<Equipment> builder = manager.getDaoSession().queryBuilder(Equipment.class);
        List<Equipment> equipmentList = builder.where(builder.and(EquipmentDao.Properties.WorkLineId.eq(id), EquipmentDao.Properties.PdxId.isNull(), builder.or(EquipmentDao.Properties.Type.eq("公用配电变压器"),
                EquipmentDao.Properties.Type.eq("公用柱上变压器"),
                EquipmentDao.Properties.Type.eq("用户专变")
        ))).list();
        return equipmentList;
    }

    public List<Equipment> queryEquipmentByLineIdAndPDX(String id) {
        QueryBuilder<Equipment> builder = manager.getDaoSession().queryBuilder(Equipment.class);
        List<Equipment> equipmentList = builder.where(EquipmentDao.Properties.PdxId.eq(id)).list();
        return equipmentList;
    }

    public List<Equipment> queryEquipmentByLineIdAndGt(String id) {
        QueryBuilder<Equipment> builder = manager.getDaoSession().queryBuilder(Equipment.class);
        List<Equipment> equipmentList = builder.where(builder.and(EquipmentDao.Properties.WorkLineId.eq(id), EquipmentDao.Properties.Type.eq("杆塔"))).orderAsc(EquipmentDao.Properties.CreateTime).list();
        return equipmentList;
    }

    public List<Equipment> queryEquipmentByLineIdNOGt(String id) {
        QueryBuilder<Equipment> builder = manager.getDaoSession().queryBuilder(Equipment.class);
        List<Equipment> equipmentList = builder.where(builder.and(EquipmentDao.Properties.WorkLineId.eq(id), EquipmentDao.Properties.Type.notEq("杆塔"))).orderAsc(EquipmentDao.Properties.CreateTime).list();
        return equipmentList;
    }

    public List<Equipment> queryEquipmentByLineIdNOGtNOBdz(String id) {
        QueryBuilder<Equipment> builder = manager.getDaoSession().queryBuilder(Equipment.class);
        List<Equipment> equipmentList = builder.where(builder.and(EquipmentDao.Properties.WorkLineId.eq(id), EquipmentDao.Properties.Type.notEq("杆塔"), EquipmentDao.Properties.Type.notEq("变电站"))).orderAsc(EquipmentDao.Properties.CreateTime).list();
        return equipmentList;
    }

    public List<Equipment> queryEquipmentByLineIdPds(String id) {
        QueryBuilder<Equipment> builder = manager.getDaoSession().queryBuilder(Equipment.class);
        List<Equipment> equipmentList = builder.where(builder.and(EquipmentDao.Properties.WorkLineId.eq(id), EquipmentDao.Properties.PdxId.eq(id))).orderAsc(EquipmentDao.Properties.CreateTime).list();
        return equipmentList;
    }


    /**
     * 查询全部数据
     */
    public List<Equipment> queryAll() {
        return manager.getDaoSession().loadAll(Equipment.class);
    }

    public JSONArray queryAllToJson() {
        JSONArray jsonArray = new JSONArray();
        List<Equipment> Equipments = queryAll();
        for (Equipment equipment : Equipments) {
            jsonArray.add(equipment.toJson());
        }
        return jsonArray;
    }

    public void insertByJsArray(JSONArray jsonArray) {
        List<Equipment> list = new ArrayList<>();
        for (int i = 0; i < jsonArray.size(); i++) {
            list.add(new Equipment(jsonArray.getJSONObject(i)));
        }
        insertMultEquipment2(list);
    }
}
